package com.bbbk.util.word;

import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.opencv.core.Core;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import lombok.extern.slf4j.Slf4j;
import pdftable.PdfTableReader;
import pdftable.PdfTableSettings;
import pdftable.models.ParsedTablePage;
@Slf4j
@Controller
public class Pdf2ExcelController {
	static boolean hasLoadOpencv = false;
	
	@RequestMapping("/pdf2Excel")
	public void pdf2Excel(HttpServletResponse response,MultipartFile file) throws Exception{
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition", "attachment;filename="+LocalDateTime.now()+".xls");
		ServletOutputStream outputStream = response.getOutputStream();
		pdfTable2Exceltest(outputStream,file);
	}
	
    public  static void pdfTable2Exceltest(OutputStream out,MultipartFile file) throws Exception {
        log.info("开始解析");
        loadLibrary();
    
        PDDocument pdfDoc = PDDocument.load(file.getInputStream());

        PdfTableSettings pdfTableSettings = new PdfTableSettings();

        //创建表格解析器
        PdfTableReader reader = new PdfTableReader(pdfTableSettings);


        //根据传入的文档和开始结束页码来解析表格 ，一个表格分页了，会变成多个表格对象
        List<ParsedTablePage> tablePages = reader.pdfTable2Excel(pdfDoc, 1, pdfDoc.getNumberOfPages(),out);
        out.flush();
        log.info("解析完成");
    }
    

    
    static void loadLibrary(){
    	String osName = System.getProperty("os.name").toLowerCase();
    	System.out.println("osName"+osName);
    	if(!hasLoadOpencv&&osName!=null&&osName.contains("win")) {
    		System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    		hasLoadOpencv = true;
    	}
    }
    
    
    @RequestMapping("/loadLibrary")
    @ResponseBody
	public String loadLibrary1(){
    	String property = System.getProperty("java.library.path");
    	System.out.println(property);
    	return property;
    }
    
    @RequestMapping("/loadLibrary2")
    @ResponseBody
	public String loadLibrary2(String path){
    	
    	System.out.println(path);
    	System.load(path);
    	return path;
    }
    
    @RequestMapping("/loadLibrary3")
    @ResponseBody
	public String loadLibrary3(String path){
    	
    	System.out.println(path);
    	System.loadLibrary(path);
    	return path;
    }
}
